package com.funny.stock.data.collect.impl;

import com.funny.stock.data.collect.StockMonitorStrategy;
import com.funny.stock.data.collect.bean.StockDataChangeEvent;
import com.funny.stock.data.collect.bean.StockMonitorContext;
import com.funny.stock.data.vo.RealtimeStockData;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;

/**
 * @author pengl
 * @date 2020/11/11
 */
@Component
public class StockDataEventManager implements ApplicationListener<StockDataChangeEvent>, InitializingBean {

//    private static final Logger logger = LoggerFactory.getLogger(StockDataEventManager.class);

    @Autowired
    TaskExecutor taskExecutor;

    @Autowired
    ApplicationContext applicationContext;

    Map<String, StockMonitorStrategy> strategyMap;

    @Override
    public void onApplicationEvent(StockDataChangeEvent event) {
        Map<String, RealtimeStockData> source = (Map) event.getSource();

        if(CollectionUtils.isEmpty(strategyMap)) return;

        StockMonitorContext context = new StockMonitorContext();
        context.setDataMap(source);

        for (String key : strategyMap.keySet()) {
            StockMonitorStrategy strategy = strategyMap.get(key);
            taskExecutor.execute(() -> strategy.onMonitor(context));
        }
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        strategyMap = applicationContext.getBeansOfType(StockMonitorStrategy.class);
    }
}
